package liujinliang.natappvip.cc.myapplication.databus;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class RxBus {
    private static volatile RxBus instance;
    private Set<DatabusSubscriber> subscribers;

    private RxBus() {
        subscribers = new CopyOnWriteArraySet<>();
    }

    public static RxBus getInstance() {
        if (instance == null) {
            synchronized (RxBus.class) {
                if (instance == null) {
                    instance = new RxBus();
                }
            }
        }
        return instance;
    }

    public void processChain(Func1 func1) {
        Observable.just("")
                .subscribeOn(Schedulers.io())
                .map(func1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1() {
                    @Override
                    public void call(Object o) {
                        for (DatabusSubscriber databusSubscriber : subscribers) {
                            databusSubscriber.onEvent(o);
                        }
                    }
                });

    }

    public void processChain(Object object, Func1 func1) {
        Observable.just(object)
                .subscribeOn(Schedulers.io())
                .map(func1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1() {
                    @Override
                    public void call(Object o) {
                        for (DatabusSubscriber databusSubscriber : subscribers) {
                            databusSubscriber.onEvent(o);
                        }
                    }
                });

    }

    public void register(DatabusSubscriber subscriber) {
        subscribers.add(subscriber);
    }

    public void unRegister(DatabusSubscriber subscriber) {
        subscribers.remove(subscriber);
    }
}
